import { useState, useEffect, useContext } from 'react';
import { NavBar, Popup, SearchBar, Tabs, List, Image, Button, InfiniteScroll, Checkbox } from 'antd-mobile';
import AvatarImage from '../../AvatarImage';

import { MySdkStoreContext } from '../../../context';

import './style.scss';

interface PropsType {
  cid: string;
  onOk: (selectedItem: any[], allInfoUsers: any[]) => void;
  onClose: () => void;
}

export default function(props: PropsType) {
  const mySdkStore = useContext(MySdkStoreContext);
  const myUserId = mySdkStore.mockConfig.userId;
  const { cid, onOk, onClose } = props;
  const [list, setList] = useState([]);
  // 是否正在”多选“操作
  const [isMultiSelecting, setIsMultiSelecting] = useState(false);
  // 已选中的@用户
  const [selectedUsers, setSelectedUsers] = useState([]);
  const [pagination, setPagination] = useState({ pageIndex: 1, totalPage: 1, totalItmeCount: 0 });

  const getList = async (pageIndex) => {
    const res =  await mySdkStore.sdk.listGroupMembers({ pageIndex, cid });
    const { rows: list = [], next, currentPageIndex } = res;
    const rows = list.filter(item => item.userId !== myUserId);
    setPagination({ pageIndex: currentPageIndex, next });
    setList(pageIndex === 1 ? rows : [...list, ...rows]);
  }

  useEffect(() => {
    getList(1);
  }, []);

  // 选中后点击”确定“处理事件
  const handleOk = (userId?: string, userInfo?: Object) => {
    let allInfoItems;
    if (userInfo) {
      allInfoItems = [userInfo];
    } else {
      allInfoItems = list.filter(item => selectedUsers.indexOf(item.userId) > -1);
    }
    if (userId) {
      if (isMultiSelecting) {
        return;
      }

      onOk([{ userId }], allInfoItems);
      return;
    }
    onOk([...selectedUsers].map(userId => ({ userId })), allInfoItems);
  }

  const renderList = () => {
    return <>
    <List style={{ '--border-inner': 0 }}>
      { !isMultiSelecting && <List.Item
          key={'__at_all__'}
          prefix={<div className="atIcon">@</div>}><div onClick={() => handleOk('__at_all__', { nickName: '所有人', userId: '__at_all__' })}>所有人</div>
        </List.Item>}
      {list.map(item => {
        return <List.Item
          key={item.userId}
          prefix={
          <>
            { isMultiSelecting && <Checkbox value={item.userId} style={{ marginRight: 12, marginBottom: 10 }} /> }
            <AvatarImage
              src={item.avatarUrl}
              nickName={item.nickName}
              userName={item.userName}
              userId={item.userId}
              style={{ display: 'inline-block', borderRadius: 8 }}
              fit='cover'
              width={36}
              height={36}
            />
        </>}><div onClick={() => handleOk(item.userId, item)}>{item.nickName || item.userName || item.userId}</div></List.Item>
      })}
    </List>
    <InfiniteScroll loadMore={() => getList(pagination.pageIndex + 1)} hasMore={pagination.pageIndex < pagination.totalPage} />
  </>
  }

  return <Popup
    visible={true}
    bodyClassName="popupbody">
      <div className="selectAtUserComponent">
        <NavBar
          onBack={onClose} style={{ background: '#fff', border: 'none' }}
          right={
            isMultiSelecting ?
              <a onClick={() => { setIsMultiSelecting(false) }} style={{ color: 'rgba(0,0,0,0.65)' }}>取消多选</a> :
              <a onClick={() => { setIsMultiSelecting(true) }} style={{ color: 'rgba(0,0,0,0.65)' }}>多选</a>
          }>选择要@的人</NavBar>
        {/* todo: listGroupMembers 没有关键词搜索参数 */}
        {/* <SearchBar className="searchBar" /> */}
        <Checkbox.Group onChange={(val) => setSelectedUsers(val)}>
          {renderList()}
        </Checkbox.Group>
        { isMultiSelecting &&
          <div className="bottomOperationBar">
            <div style={{ lineHeight: '29px' }}>已选择：{selectedUsers.length}人</div>
            <Button color="primary" size="small" onClick={() => handleOk()} disabled={ !selectedUsers.length }>确定</Button>
          </div> }
      </div>
  </Popup>;
}